package au.com.centrumsystems.hudson.plugin.util.revision;

import hudson.model.AbstractBuild;
import hudson.model.Hudson;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

public class HgExtractor extends Extractor {

    private static final Logger LOGGER = Logger.getLogger(HgExtractor.class.getName());

    /**
     * Returns the last hg rev
     * 
     * @return revision number of the current build
     */
    @Override
    protected String doExtract(AbstractBuild<?,?> build)
    throws MalformedURLException, IOException {
        InputStream inputStream = null;
        try {
            String revNo = null;
            final URL url = new URL(Hudson.getInstance().getRootUrl() + build.getUrl() + "api/json?tree=changeSet[items[node,rev]]");
            inputStream = url.openStream();
            final JSONObject json = (JSONObject) JSONSerializer.toJSON(IOUtils.toString(inputStream));
            if (json != null) {
                try {

                    final JSONArray items = json.getJSONObject("changeSet").getJSONArray("items");
                    if (items != null && items.size() >= 1) {
                        revNo = "Hg: " + items.getJSONObject(0).getString("rev") + ":" + items.getJSONObject(0).getString("node");
                    }
                } catch (final JSONException e) {
                    // This is not great, but swallow jquery parsing exceptions assuming that some element did not exist, will have a better
                    // solution one I find a JSON query lib or method
                    LOGGER.finest("did not find svn revision in " + json);
                }
            }
            return revNo;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (final IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

